<template>
  <div>
    <van-field
      :value="selectLabel"
      v-bind="$attrs"
      @click="clickShow()"
    />
    <van-popup v-model="showPicker" position="bottom">
      <slot></slot>
      <div style="padding: 10px;width: 100%;text-align: center" v-if="clearable">
        <van-tag style="padding: 5px" @click="clearSelect" >清除选择</van-tag>
      </div>
      <van-picker
        show-toolbar
        :columns="optionsLabel"
        @confirm="onConfirm"
        @cancel="showPicker = false"
      >
      </van-picker>
    </van-popup>
  </div>
</template>

<script>
  import BaseVan from './BaseVan'

  export default {
    name: 'ZbVanSelect',
    extends:BaseVan,
    model: {
      prop: "selectValue",
      event: "input"
    },
    props:{
      options:{
        default:[],
        type:Array,
      },
      showToast:{
        default:false,
        type:Boolean,
      },
      clearable:{
        default:false,
        type:Boolean,
      },
      prop:{
        default: {
          label:'label',
          value:'value',
        },
        type:Object,
      }
    },
    watch:{
      options:{
        handler(){
          this.optionsLabel = []
          this.optionsValue = []
          for (let i = 0; i < this.options.length; i++) {
            this.optionsLabel.push(this.options[i][this.prop['label']])
            this.optionsValue.push(this.options[i][this.prop['value']])
          }
        },
        deep:true,
        immediate:true
      },
    },
    data(){
      return {
        optionsLabel: [],
        optionsValue: [],
        selectValue: '',
        selectLabel: '',
        showPicker: false,
      }
    },
    created () {
    },
    methods:{
      clickShow(){
        this.showPicker = true
        this.$emit('click')
      },
      clearSelect(){
        this.selectValue = ''
        this.selectLabel = ''
        this.showPicker = false
        this.$emit('input',this.selectValue)
        if (this.showToast){
          this.Toast(`清除成功`)
        }
      },
      onConfirm(val,index){
        this.selectValue = this.optionsValue[index]
        this.selectLabel = this.optionsLabel[index]
        this.showPicker = false
        this.$emit('input',this.selectValue)
        if (this.showToast){
          this.Toast(`选择成功`)
        }
      }
    }
  }
</script>
